const express = require("express");
const router = express.Router();
const adminRouter = express.Router();
const { resData } = require("../../utils/format");
const UserModel = require("../../models/User");
const assert = require("http-assert");
const middleware_auth = require("../../middleware/auth");
const middleware_resource = require("../../middleware/resource");
const middleware_permission = require("../../middleware/permission");
const menuServe = require("./menu");
const roleServe = require("./role");
const pageServe = require("./page");
module.exports = app => {
    /**
     * @apiGroup 管理端根路由
     * @api {post} /admin/api/rest/:resource 通用新增
     * @apiParam {String} resource  模型名(小写复数)
     */
    router.post("/", async (req, res) => {
        let message = "新增成功";
        switch (req.commonModel.modelName) {
            case "User":
                const { username, password, role, email } = req.body;
                assert(username, 400, "请传入username");
                req.body.username = String(username);
                assert(email, 400, "请输入email");
                req.body.email = String(email);
                assert(password, 400, "请传入password");
                req.body.password = String(password);
                assert(role, 400, "请传入role");
                const commonUser = await UserModel.findOne({ username });
                commonUser ? assert(false, 401, "用户名已存在") : false;
                message = "注册成功";
                break;
            case "Permission":
                const { key, role: myRole } = req.body;
                assert(key, 400, "请传入key");
                assert(myRole, 400, "请传入role");
                const commonPermission = await PermissionModel.findOne({ key });
                commonPermission ? assert(false, 400, "该权限已存在") : false;
                break;
            case "Category":
                const { title, cover } = req.body;
                assert(title, 400, "请传入title");
                break;
            case "Swiper":
                const { cover: siperCover, link, desc, available = true } = req.body;
                req.body.available = available;
                assert(siperCover, 400, "请传入cover");
                // assert(link, 400, "请传入link");
                // assert(desc, 400, "请传入desc");
                break;
        }
        const data = await req.commonModel.create(req.body);
        res.send(resData(data, { message }));
    });
    /**
     * @apiGroup 管理端根路由
     * @api {delete} /admin/api/rest/:resource 通用删除
     * @apiParam {String} resource  模型名(小写复数)
     */
    router.delete("/", async (req, res) => {
        const { _id } = req.body;
        assert(_id, 400, "请传入id");
        switch (req.commonModel.modelName) {
            case "Menu":
                const findChild = await req.commonModel.find({ parentId: _id });
                assert(!findChild.length, 400, "该菜单下还有子菜单");
        }
        const deleteItem = await req.commonModel.findByIdAndDelete(_id);
        res.send(resData(deleteItem, { message: "删除成功" }));
    });
    /**
     * @apiGroup 管理端根路由
     * @api {patch} /admin/api/rest/:resource 通用修改
     * @apiParam {String} resource  模型名(小写复数)
     */
    router.patch("/", async (req, res) => {
        const { _id } = req.body;
        assert(_id, 400, "请传入id");
        const oldItem = await req.commonModel.findByIdAndUpdate(_id, req.body);
        const newItem = await req.commonModel.findById(_id);
        switch (req.commonModel.modelName) {
            case "Menu":
                req.session.permissionMenus = null;
                break;
        }
        res.send(resData({ oldItem, newItem }, { message: "修改成功" }));
    });
    /**
     * @apiGroup 管理端根路由
     * @api {get} /admin/api/rest/:resource 通用查询
     * @apiParam {String} resource  模型名(小写复数)
     */
    router.get("/", async (req, res) => {
        let { current = 1, pageSize = 10 } = req.query;
        current = Number(current);
        pageSize = Number(pageSize);
        let queryOptions = {};
        switch (req.commonModel.modelName) {
            case "Commodity":
                queryOptions.populate = "cat";
                break;
            case "HomeConfig":
                queryOptions.populate = ["icons", "swipers", "hotSearches"];
                break;
            case "Icon":
                queryOptions.populate = ["prdId", "pageId"];
        }
        let data = await req.commonModel
            .find()
            .sort({ updateTime: -1 })
            .setOptions(queryOptions)
            .skip((current - 1) * pageSize)
            .limit(pageSize);
        switch (req.commonModel.modelName) {
            case "Menu":
                let deepData = JSON.parse(JSON.stringify(data));
                let parentList = deepData.filter(item => !item.parentId);
                let childList = deepData.filter(item => item.parentId);
                let translateDataToTree = (parents, children) => {
                    parents.forEach(parentItem => {
                        children.forEach((childItem, childIndex) => {
                            if (String(parentItem._id) == String(childItem.parentId)) {
                                let temp = JSON.parse(JSON.stringify(children));
                                temp.splice(childIndex, 1);
                                translateDataToTree([childItem], temp);
                                if (parentItem.children) {
                                    parentItem.children.push(childItem);
                                } else {
                                    parentItem.children = [childItem];
                                }
                            }
                        });
                    });
                };
                translateDataToTree(parentList, childList);
                data = parentList;
                break;
        }
        const total = await req.commonModel.find().countDocuments();
        res.send(resData(data, { current, pageSize, total }));
    });
    //通用crud主服务，子服务挂载到上面
    app.use("/admin/api/rest/:resource", middleware_auth(), middleware_resource(), middleware_permission(), router);
    /**
     * @apiGroup 管理端根路由
     * @api {post} /admin/api/info 获取用户信息
     */
    //主服务，子服务挂载到上面
    adminRouter.get("/info", (req, res) => {
        const { user } = req.session;
        res.send(resData(user));
    });
    app.use("/admin/api", middleware_auth(), middleware_permission(), adminRouter);
    menuServe(app);
    roleServe(app);
    pageServe(app);
};
